import html
import time
from base64 import b64encode

from pywebio.output import *


class WebClient:
    def __init__(self):
        self.init_page()

    def init_page(self):
        img = open('00001.jpg', 'rb').read()
        style([put_image(img, width='100%')], 'position:fixed;left: 0px;top:0px;opacity: 0.6;')
        style([put_scope("list")], 'display:flex;flex-flow: wrap;')

    def clear_container(self):
        clear("list")

    def add_user(self, name, text):
        print(name, text)
        img = open('touxiang.jpg', 'rb').read()
        tpl = '''
            <div style="position: relative;display:flex;margin-top:28px;margin-left:5px;width:150px">
                 {{#image}}
                    {{& pywebio_output_parse}}
                 {{/image}}
            <div style="font-size: 11px;line-height: 30px;height: 30px;color:red;margin-left:2px;
                        overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
                {{name}}
            </div>
            <div style="position:absolute;top:-23px;color:blue;background:lightgray;border-radius:4px;padding:2px 3px;
                        font-size: 10px;width:95%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
                {{text}}
            </div>
            </div>
            '''
        put_widget(tpl, {"name": name, "text": text, "image": [self.put_img(img, width='30', height='30')]}, "list")

    @staticmethod
    def put_img(src, format=None, width=None, height=None):
        b64content = b64encode(src).decode('ascii')
        format = '' if format is None else ('image/%s' % format)
        format = html.escape(format, quote=True)
        src = "data:{format};base64, {b64content}".format(format=format, b64content=b64content)
        tag = r'<img src="{src}" style="width:{width}px;height:{height}px;border-radius: 50%"/>' \
            .format(src=src, height=height, width=width)
        return put_html(tag)


if __name__ == '__main__':
    webClient = WebClient()
    for i in range(0, 100):
        webClient.add_user("张三{i}".format(i=i), "哈哈哈{i}".format(i=i))
        time.sleep(1)
